package com.talent.carrot.C_publish_subscribe;

import com.rabbitmq.client.*;
import com.talent.carrot.B_workqueues.Task;
import org.yaml.snakeyaml.Yaml;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 躲了一辈子雨，雨会不会很难过。
 * </p>
 * Created by zhumenglong on 2017/6/18.
 */
public class EmitLog {

    private static final String EXCHANGE_NAME = "logs";

    private static InputStream rabbitConfig;

    private static Map configMap;

    static {
        rabbitConfig = Task.class.getClassLoader().getResourceAsStream("RabbitMqConfig.yaml");
    }

    public static void main(String[] argv) throws Exception {

        Yaml yaml = new Yaml();
        configMap = (HashMap<String, String>) yaml.load(rabbitConfig);

        ConnectionFactory factory = new ConnectionFactory();
        //指定主机
        factory.setHost((String) configMap.get("CF.Host"));
        //指定用户 密码
        factory.setUsername((String) configMap.get("CF.Username"));
        factory.setPassword((String) configMap.get("CF.Password"));
        //指定端口
        factory.setPort(AMQP.PROTOCOL.PORT);

        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.FANOUT);

        String message = getMessage(argv);

        channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes("UTF-8"));
        System.out.println(" [x] Sent '" + message + "'");

        channel.close();
        connection.close();
    }

    private static String getMessage(String[] strings) {
        if (strings.length < 1)
            return "info: Hello World!";
        return joinStrings(strings, " ");
    }

    private static String joinStrings(String[] strings, String delimiter) {
        int length = strings.length;
        if (length == 0) return "";
        StringBuilder words = new StringBuilder(strings[0]);
        for (int i = 1; i < length; i++) {
            words.append(delimiter).append(strings[i]);
        }
        return words.toString();
    }
}
